﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Xml.Linq;

namespace Web.Framework.Translate
{
    public class LocalizationProvider
    {
        private static LocalizationProvider _instance;

        private string translationFilePath = string.Empty;

        private Dictionary<string, string> _innerDictionary = new Dictionary<string, string>();

        public static void InitalizeInstance(string translationFilePath)
        {
            _instance = new LocalizationProvider();
            _instance.translationFilePath = translationFilePath;

            _instance.ReInitialize();
        }

        public static void InitalizeInstance(Dictionary<string, string> terms)
        {
            _instance = new LocalizationProvider();
            _instance._innerDictionary = terms;            
        }

        public void ReInitialize()
        {
            _innerDictionary.Clear();
            XDocument doc = XDocument.Load(translationFilePath);

            var terms = from xterm in doc.Descendants()
                        where xterm.Name == "term"
                        select xterm;

            // Cargo los valores del xml a memoria
            foreach (var term in terms)
            {
                if (!String.IsNullOrEmpty(term.Attribute("key").Value))
                {
                    _instance._innerDictionary.Add(term.Attribute("key").Value, term.Value);
                }
            }
        }

        public string this[string key]
        {
            get
            {
                string returnValue = string.Empty;               

                if(_innerDictionary.ContainsKey(key))
                {
                    returnValue = _innerDictionary[key];
                }

                return returnValue;
            }
        }

        public static LocalizationProvider Instance
        {
            get
            {
                return _instance;
            }
        }
    }
}
